<?php

/**
 * PostsController
 * 
 * 
 * @category   Controller
 * @package    PostsController
 * @subpackage AppController
 * @copyright  Copyright (c) 2012 Victor Rosset
 * @license    
 * @version    0.1 alpha
 * @link       http://www.tucho235.com.ar
 * @since      25-ago-2012
 * @author     Victor Rosset <victorrosset@gmail.com> @tucho235
 * @php        5.3.13
 * 
 */
 
class PostsController extends AppController
{
    
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');


    public function beforeFilter() {
        parent::beforeFilter();
    }

    public function add() {
        if ($this->request->is('post')) {
            $postData = $this->request->data;
            $this->request->data['Post']['user_id'] = $this->Auth->user('id'); //Added this line
            if ($this->Post->save($postData)) {
                $this->Session->setFlash(__('El Post ha sido guardado'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('El Post no se pudo guardar'));
            }
        }
        $this->render('/Posts/add');
    }
    
    public function delete($id) {
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Post->delete($id)) {
            $this->Session->setFlash(__('El Post con id:') . ' ' . $id . ' ' . __('ha sido eliminado'));
            $this->redirect(array('action' => 'index'));
        }
    }
    
    public function edit($id = null) {
        $this->Post->id = $id;
        if ($this->request->is('get')) {
            $this->request->data = $this->Post->read();
        } else {
            $post = $this->request->data;
            if ($this->Post->save($post)) {
                $this->Session->setFlash(__('El Post ha sido actualizado'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('El Post no se pudo actualizar'));
            }
        }
        $this->render('/Posts/edit');
    }
    
    public function index() {
        $posts = $this->Post->find('all');
        $this->set(compact('posts'));
        $this->render('/Posts/index');
    }
    
    public function view($id = null) {
        $this->Post->id = $id;
        $post = $this->Post->read();
        $this->set(compact('post'));
        $this->render('/Posts/view');        
    }
    
    
    public function isAuthorized($user) {
        // All registered users can add posts
        if ($this->action === 'add') {
            return true;
        }

        // The owner of a post can edit and delete it
        if (in_array($this->action, array('edit', 'delete'))) {
            $postId = $this->request->params['pass'][0];
            if ($this->Post->isOwnedBy($postId, $user['id'])) {
                return true;
            }
        }
        return parent::isAuthorized($user);
    }


}